package com.yige.service.mongoService

import com.mongodb.BasicDBObject
import com.mongodb.DBCollection
import com.mongodb.DBObject
import com.yige.common.MD5Util
import com.yige.common.SystemConstant
import com.yige.service.UserService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service

/**
 * Created by sunhao on 2015/9/17 0017.
 */

@Service
class MongoUserService extends BasicMongoServiceImp implements UserService {

    @Autowired
    MongoRoleService roleService
    @Autowired
    MongoResourceService resourceService

    DBCollection getCollection(){
        return mongoTemplate.getCollection(SystemConstant.MONGODB_COL_USER)
    }

    @Override
    DBObject findUserByName(String username) {
        def query = [username:username] as BasicDBObject
        return findOneByQuery(query)
    }

    @Override
    boolean updatePwd(DBObject user, String lastPwd, String newPwd) {
        DBObject user_db = findOneById(user._id)
        if((user_db.password).equals(MD5Util.md5(lastPwd))){
            getCollection().update(
                    [_id:user._id]as BasicDBObject,
                    [$set: [password:MD5Util.md5(newPwd)]as BasicDBObject]as BasicDBObject
            )
            return true
        }else{
            return false
        }
    }

    @Override
    List<DBObject> findAllRoleByUser(Object userId) {
        DBObject user = findOneById(userId)
        List<DBObject> roleList = user.role
        return roleList
    }

    @Override
    boolean bindRoleForUser(Object userId, Object roleId) {
        List<DBObject> roleList = findAllRoleByUser(userId)
        roleList.add(roleId)
        updateRoleForUser(userId,roleList)
        return true
    }

    @Override
    boolean removeRoleForUser(Object userId, Object roleId) {
        List<DBObject> roleList = findAllRoleByUser(userId)
        roleList.remove(roleId)
        updateRoleForUser(userId,roleList)
        return true
    }

    @Override
    boolean updateRoleForUser(Object userId, List<DBObject> roles) {
        return getCollection().update(
                [_id:userId]as BasicDBObject,[$set:[role:roles]as BasicDBObject]as BasicDBObject
        )
    }

    @Override
    List<String> findUserAuth(DBObject user) {
        def authList = new ArrayList(),
            resourceList,roleList
        DBObject resource
        roleList = findAllRoleByUser(user._id)
        roleList.each {roleId->
            resourceList = roleService.findAllResourceForRole(roleId)
            resourceList.each {resourceId->
                resource = resourceService.findOneById(resourceId)
                authList.add(resource.url)
            }
        }
        return authList
    }
}
